package com.turing.manage.listener;
import javax.servlet.ServletContext;
/**
 * @desc   监听器实现在线人员的统计
 * @author wyh
 * @time   2022-01-06
 */
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener {

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		System.out.println("sessionCreated()");
		System.out.println("session开始创建，且id="+se.getSession().getId());
		//1.立足se事件对象获取servletContext对象
		ServletContext ctx = se.getSession().getServletContext();
		
		//2.从application作用域中取出名字叫numsessions属性对应的值
		Integer numsessions = (Integer) ctx.getAttribute("numsessions");
		
		
		//3.判断是否是第一用户登录
		if (numsessions==null) 
		{
		numsessions=new Integer(1);//给numsessions赋值为1	
		}
		else//4.从第一个用户登录之后的其他用户即默认自动加1
		{
	     int count = numsessions.intValue();
	     numsessions=new Integer(count+1);
		}
		
		//5.存入到application作用域中
		ctx.setAttribute("numsessions", numsessions);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		  System.out.println("sessionDestroyed()");
		  System.out.println("session销毁了，且id="+se.getSession().getId());
		
		    ServletContext ctx=se.getSession().getServletContext();  
		    Integer numSessions = (Integer)ctx.getAttribute("numSessions");  
		    if(numSessions == null) { 
		        numSessions = new Integer(0);  
		    }  
		    else {  
		        int count = numSessions.intValue( );  
		        numSessions = new Integer(count - 1);  
		    }  
		    ctx.setAttribute("numSessions", numSessions);
		
		
	}

}
